// stores/product.store.ts
import { defineStore } from 'pinia'
// import { useNuxtApp } from '#app'

export const useProductStore = defineStore('product', () => {
  // 状态
  const { $request } = useNuxtApp()
  const products = ref([])
  const isLoading = ref(false)
  const error = ref(null)
  
  const keyword = ref(null)

  const ParentIDs = ref()
  const CategoryIDs = ref()
  const MFGIDs = ref()

  const Page = ref(1)
  const pageSize = ref(20)
  const PageInfo = ref({
    TotalPage: 0,
    TotalResult: 0,
  })
  
  // Action：获取产品数据
  const fetchProducts = async () => {
    try {
      isLoading.value = true
      error.value = null
      const params = {
        Limit: pageSize.value,
        Page: Page.value,
        KeyWord: keyword.value,
      }
      if (ParentIDs.value) {
        params.ParentIDs = [ParentIDs.value];
      }
      if (CategoryIDs.value) {
        params.CategoryIDs = [CategoryIDs.value];
      }
      if (MFGIDs.value) {
        params.MFGIDs = [MFGIDs.value];
      }
      // 使用 Nuxt 3 的 $fetch 发起请求
      const response = await  $request.post('/api/v1/partno/partnosearchasync', params)
      
      products.value = response.Data.PartNoListModels
      PageInfo.value.TotalPage = response.Data.TotalPage
      PageInfo.value.TotalResult = response.Data.TotalResult
    } catch (err) {
      error.value = 'get product info error'
      products.value = []
      console.error(err)
    } finally {
      isLoading.value = false
    }
  }

  // 修改搜索关键字
  const setKeyword = (value) => {
    keyword.value = value
  }

  // 修改筛选条件
  const setFilter = (filter) => {
    ParentIDs.value = filter.parent
    CategoryIDs.value = filter.category
    MFGIDs.value = filter.brand
    console.log(ParentIDs.value, CategoryIDs.value, MFGIDs.value);
    fetchProducts()
  }

  // 修改页码
  const setPage = (value) => {
    Page.value = value
    fetchProducts()
  }

  // 修改pagesize
  const setPageSize = (value) => {
    pageSize.value = value
    fetchProducts()
  }

  return {
    products,
    isLoading,
    error,
    Page,
    pageSize,
    PageInfo,
    fetchProducts,
    setFilter,
    setKeyword,
    setPage,
    setPageSize
  }
})